package com.msy;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import javax.sql.DataSource;

/**
 * @author Irving
 */
@SpringBootApplication
@MapperScan(basePackages = {"com.msy.mapper"})
public class MySQLConnectorApplication {

    /**
     * 建表SQL
     */
    @Value("classpath:db/schema.sql")
    private Resource schema;
    /**
     * 插入数据SQL
     */
    @Value("classpath:db/data.sql")
    private Resource data;

    public static void main(String[] args) {
        SpringApplication.run(MySQLConnectorApplication.class, args);
    }

    /**
     * 数据库初始化时执行SQL文件
     * @param dataSource
     * @return
     */
    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource){
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(databasePopulator());
        return dataSourceInitializer;
    }

    private DatabasePopulator databasePopulator(){
        ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.addScript(schema);
        resourceDatabasePopulator.addScript(data);
        // 分隔符，默认为;
        resourceDatabasePopulator.setSeparator("$$$");
        return resourceDatabasePopulator;
    }
}
